#nullable enable
using Godot;
using System.Collections.Generic;

namespace AndroidUnevenRoadGame.Game
{
    public static class PotionDatabase
    {
        private static readonly Dictionary<string, PotionDefinition> _potions = new();
        private static bool _isLoaded;

        public static void LoadFromJson(string resourcePath)
        {
            if (_isLoaded)
            {
                return;
            }

            var file = FileAccess.Open(resourcePath, FileAccess.ModeFlags.Read);
            if (file == null)
            {
                GD.PushWarning($"无法打开药剂配置：{resourcePath}");
                return;
            }

            var jsonText = file.GetAsText();
            file.Dispose();

            var result = Json.ParseString(jsonText);
            if (result.VariantType != Variant.Type.Array)
            {
                GD.PushWarning("药剂配置格式错误：根节点需要为数组");
                return;
            }

            foreach (Variant entryVar in result.AsGodotArray())
            {
                if (entryVar.VariantType != Variant.Type.Dictionary)
                {
                    continue;
                }

                var dict = entryVar.AsGodotDictionary();
                var id = dict.TryGetValue("id", out var idVar) && idVar.VariantType == Variant.Type.String ? idVar.AsString() : "potion";
                var name = dict.TryGetValue("name", out var nameVar) && nameVar.VariantType == Variant.Type.String ? nameVar.AsString() : id;
                var description = dict.TryGetValue("description", out var descVar) && descVar.VariantType == Variant.Type.String ? descVar.AsString() : string.Empty;

                _potions[id] = new PotionDefinition(id, name, description);
            }

            _isLoaded = true;
        }

        public static PotionDefinition Get(string id)
        {
            if (_potions.TryGetValue(id, out var definition))
            {
                return definition;
            }

            GD.PushWarning($"未找到药剂：{id}");
            return new PotionDefinition(id, id, string.Empty);
        }

        public static string? GetRandomPotionId(RandomNumberGenerator rng)
        {
            if (_potions.Count == 0)
            {
                return null;
            }

            var keys = new List<string>(_potions.Keys);
            var index = rng.RandiRange(0, keys.Count - 1);
            return keys[index];
        }
    }
}

